package project;
import oracle.kv.*;

/**
 * Initialisation de l'etape 3
 */
public class Init_balance {

	// numbre de item dans chaque store
	public static final int storeSize = 500;
	// nombre de store
	public static final int N = 1000 / storeSize;
	// les stores
	public static Store[] stores;

	/**
	 * la fonction principale de l'initialisation
	 */
	public static void main(String args[]) {
		try {
			Init_balance application = new Init_balance();
			application.init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * Initialisation de configuration
	 * */
	private Init_balance() {

		String[] storeNames = new String[N];
		storeNames[0] = "kvstore";
		storeNames[1] = "kvstore";
		String[] hostNames = new String[N];
		hostNames[0] = "ari-31-312-14";
		hostNames[1] = "ari-31-312-15";
		String[] hostPorts = new String[N];
		hostPorts[0] = "5000";
		hostPorts[1] = "5000";

		stores = new Store[N];
		for (int i = 0; i < N; i++) {
			stores[i] = new Store();
			stores[i].setStore(KVStoreFactory.getStore(new KVStoreConfig(
					storeNames[i], hostNames[i] + ":" + hostPorts[i])));
		}
	}

	public void init() {
		// initialiser la base de donnees
		for (int i = 1; i <= 1000; i++) {
			Key key = Key.createKey("P" + i, "quality");
			int indexStore = hachage(i);
			String data = "0";
			// creer la version de donner
			Value value = Value.createValue(data.getBytes());
			stores[indexStore].getStore().put(key, value);
			stores[indexStore].getVersions().put(i, 1);
		}
		// TEST - START
		Key k1 = Key.createKey("P" + 500, "quality");
		int indexStore = hachage(500);
		System.out.println(indexStore);
		ValueVersion valueVersion = stores[indexStore].getStore().get(k1);
		System.out.println(k1.toString() + " "
				+ new String(valueVersion.getValue().getValue()));
		// TEST - END
		for (int i = 0; i < N; i++)
			stores[i].getStore().close();
	}

	/**
	 * Fonction de hachage.
	 * */
	public int hachage(int i) {
		int y = 0;
		if (i >= 0 && i <= 1000)
			y = (i - 1) / Init_balance.storeSize;
		else
			y = -1;
		return y;
	}
}